<template>
  <div>
    <zm-panel title="添加产品" :visible.sync="value" @change="close">
      <zm-form :model="form" ref="searchForm" class="mt20" inline>
        <zm-form-item prop="productType">
          <zm-data-select
            v-model="form.productType"
            :list="productTypeList"
            class="w200"
            clearable
            placeholder="产品类型"
            multiple
            str
>
          </zm-data-select>
        </zm-form-item>
        <zm-form-item prop="name">
          <zm-input
            v-model="form.name"
            class="w200"
            placeholder="请输入商品名搜索"
          ></zm-input>
        </zm-form-item>
        <zm-form-item prop="businessType">
          <zm-data-select
            v-model="form.businessType"
            :list="BUSINESS_TYPE"
            class="w150"
            clearable
            placeholder="业务类型"
            multiple
            str
          >
          </zm-data-select>
        </zm-form-item>
        <zm-form-item prop="exchangeRange">
          <zm-data-select
            v-model="form.exchangeRange"
            :list="PRODUCT_EXCHANGE"
            class="w150"
            clearable
            placeholder="兑换范围"
            multiple
            str
          >
          </zm-data-select>
        </zm-form-item>
        <zm-form-item prop="apartmentId">
         <tree-select
            v-model="form.apartmentId"
            :tree="apartmentList"
            :tree-props="{ label: 'name', valueKey: 'value' }"
            :is-checkbox="true"
            placeholder="可售部门"
            class="dib"
          ></tree-select>
        </zm-form-item>
        <zm-form-item>
          <zm-button type="primary" @click="onSearch">查询</zm-button>
          <zm-button type="warning" @click="onReset" t="reset"></zm-button>
        </zm-form-item>
      </zm-form>
      <h4>
        已选产品数：（
        <span class="fc-blue">{{ innerChecked.length }}</span>
        ）
      </h4>
      <zm-table-data
        v-loading="loading"
        :data="tableParams.data"
        :columns="columns"
        :fetch="loadList"
        :table-params="tableParams"
        :show-page="true"
        :checked="checkedArr"
      >
      </zm-table-data>
      <div slot="footer" class="tr">
        <el-button @click="close" type="info">返回</el-button>
        <el-button @click="submit" type="primary">确定</el-button>
      </div>
    </zm-panel>
    <!-- 产品详情 -->
    <detail-container
      v-if="isShowDetail"
      v-model="isShowDetail"
      :id="detailID"
      :is-show-btn="false"
    ></detail-container>
     <physical-product-config-detail v-model="PhysicalDetailParams.visible" v-if="PhysicalDetailParams.visible" :obj="PhysicalDetailParams.obj" :id="detailID"></physical-product-config-detail>
  </div>
</template>
<script>
import panelMixin from '@/mixins/panelMixin'
import tableMixin from '@/mixins/zmTableMixin'
import productApis from '@/api/src/product'
import publicApis from '@/api/src/public'
import DetailContainer from '@/components/DetailContainer'
import physicalProductConfigDetail from '@/views/product/physicalProductConfig/components/physicalProductConfigDetail'
import { columns } from './const'
import TreeSelect from '@/components/TreeSelect'
import {BUSINESS_TYPE, PRODUCT_EXCHANGE} from '@/model'
import { removeDuplication } from '@/utils'
export default {
  name: 'SelectProduct',
  components: {DetailContainer, TreeSelect, physicalProductConfigDetail},
  mixins: [panelMixin, tableMixin],
  props: {
    checkedArr: {
      // 回填数组,id集合
      type: Array,
      default () {
        return []
      }
    },
    // 查询参数
    params: {
      type: Object,
      default: () => {}
    },
    // 是否为次卡
    isTimeCar: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      BUSINESS_TYPE,
      PRODUCT_EXCHANGE,
      detailID: '',
      isShowDetail: false,
      PhysicalDetailParams: {
        visible: false,
        obj: {}
      },
      form: {
        name: '', // 名称
        businessType: '', // 业务类型
        productType: '', // 产品类型1兑换券，2卖品券，3点卡，4次卡，5优惠券
        exchangeRange: '', // 兑换范围
        apartmentId: '', // 部门id
        checkStatus: '3' // 审批状态 3 已通过
      },
      apartmentList: [],
      innerChecked: [],
      productTypeList: [],
      loading: false
    }
  },
  computed: {
    columns () {
      return columns(this)
    },
    isCheckAll: {
      get () {
        const res = this.tableParams.data.filter(i => i.isChecked)
        const isCheckedLen = res.length
        const currentPageDataLen = this.tableParams.data.length
        return isCheckedLen === currentPageDataLen
      },
      set (v) {
        console.log(v)
      }
    },
    tableAllId () { // 当前页的数据ID集合
      return this.tableParams.data.map(item => item.id)
    }
  },
  watch: {},
  created () {
    this.init()
  },
  methods: {
    async init () {
      if (this.checkedArr && this.checkedArr.length > 0) {
        this.innerChecked = JSON.parse(JSON.stringify(this.checkedArr))
      }
      this.apartmentList = await publicApis.apartmentList()
      const _res = await publicApis.getDictList({type: 'productType'})
      if (this.isTimeCar) {
        const arr = ['1', '2', '5']
        this.productTypeList = _res.filter(item => {
          return arr.includes(item.value)
        })
      } else {
        this.productTypeList = _res
      }
    },
    async loadList (type) {
      this.loading = true
      if (this.isTimeCar) {
        this.form.productType = '1,2,5'
      }
      const _res = await productApis.getPageList(this.assignQuery(this.form))
      const list = _res.list.map(item => {
        const isChecked = this.innerChecked.includes(item.id)
        return {
          ...item,
          isChecked
        }
      })
      this.initialTableData(list, _res.count)
      this.loading = false
    },
    initialTableData (dataList, totalCount) {
      const tableParams = this.tableParams
      tableParams.total = totalCount || 0
      tableParams.data = dataList || []
    },
    onDetail (row) {
      if (+row.type !== 6) {
        this.isShowDetail = true
      } else {
        this.PhysicalDetailParams = {
          visible: true,
          obj: row
        }
      }
      this.detailID = row.id
    },
    selectAll (e) {
      if (e) {
        this.tableParams.data = this.tableParams.data.map(item => ({
          ...item,
          isChecked: true
        }))
        const duplicationArr = [...this.innerChecked, ...this.tableAllId]
        this.innerChecked = Array.from(new Set(duplicationArr))
      } else {
        this.tableParams.data = this.tableParams.data.map(item => ({
          ...item,
          isChecked: false
        }))
        this.innerChecked = this.innerChecked.filter(item => {
          return !this.tableAllId.includes(item)
        })
      }
    },
    selectRow (e, row, index) {
      // index 来自表格
      const _row = { ...row, isChecked: e }
      this.$set(this.tableParams.data, index, _row)
      if (e) {
        this.innerChecked.push(row.id)
      } else {
        this.innerChecked = this.innerChecked.filter(i => i !== row.id)
      }
    },
    submit () {
      this.$emit('handle-after', this.innerChecked)
      this.close()
    }
  }
}
</script>
<style scoped lang='scss'>
</style>
